﻿using AutoMapper;
using B.S.BaseData.Domain.Entities.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.WriteAPI.Applications.Commands.Users;
using MD5Hash;
using MediatR;

namespace B.S.BaseData.WriteAPI.Applications.Handlers.Users
{
    public class AddUserHandler : IRequestHandler<AddUserCommand, ApiResult>
    {
        private readonly IUserRepository userRep;
        private readonly IMapper mapper;

        public AddUserHandler(IUserRepository userRep,IMapper mapper)
        {
            this.userRep = userRep;
            this.mapper = mapper;
        }
        public async Task<ApiResult> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            // 1. 参数校验
            if (request?.user == null || string.IsNullOrWhiteSpace(request.user.UserName))
            {
                return ApiResult.Fail("用户信息不能为空", StatusCodeEnum.Fail);
            }

            // 2. 检查用户名是否已存在
            var existUser = await userRep.GetAsync(u => u.UserName == request.user.UserName);
            if (existUser != null)
            {
                return ApiResult.Fail("用户名已存在", StatusCodeEnum.UserExist);
            }

            request.user.Password = request.user.Password.GetMD5();

            var userDto = mapper.Map<User>(request.user);

            // 3. 添加用户
            var addResult = await userRep.AddAsync(userDto);
            if (addResult > 0)
            {
                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            else
            {
                return ApiResult.Fail("添加用户失败", StatusCodeEnum.Fail);
            }
        }
    }
}
